package com.example.demo.WebMvcConfigurer;

import com.example.demo.entity.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * WebMvcConfigurer 用来全局定制化SpringBoot 的MVC 特性
 * 通过实现WebMvcConfigurer接口来配置应用的MVC全局特性
 * 采用JavaBean方式只需要添加一个web相关配置的类型，并且配置@Configuration注解，将该配置类托管给Spring IOC完成配置
 */
@Configuration
public class MvcConfigurer implements WebMvcConfigurer {
    //格式化
    @Override
    public void addFormatters(FormatterRegistry registry) {

    }
    //拦截器
    /*@Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册拦截器，检查会话，URI以test开头的都使用此拦截器
        registry.addInterceptor(new SessionHandlerInterceptor()).addPathPatterns("/test/**");
        registry.addInterceptor(new SessionHandlerInterceptor()).addPathPatterns("/testXX/**")
                                                                .addPathPatterns("/testXXX/**");
    }
    class SessionHandlerInterceptor implements HandlerInterceptor{
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //在调用Controller方法之前调用此方法
            User user = (User)request.getSession().getAttribute("user");
            if(user==null){
                //如果没有登录，处理。。。
                response.sendRedirect("/login.html");
                return false;
            }
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            //Controller方法处理完后页面渲染之前，调用此方法
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            //页面渲染完毕后调用此方法，通常做清除某些资源，类似finally
        }
    }*/

    //跨域访问配置
    /*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/test/**")//限定访问/test路径
                .allowedOrigins("http:127.0.0.1")//只允许来自这个地址跨域访问
                .allowedMethods("GET","POST");//允许的方法
    }*/
    //URI 到视图的映射
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

    }
    //其他更多全局定制接口。。。
}
